﻿using DuiBa.Models;
using DuiBa.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;

namespace DuiBa
{
    public static class DuiBaSDK
    {
        public static string AppSecret { get { return "2LJ6AQo6gAtXPtequ8sCfayJS7oH"; } }
        public static string AppKey { get { return "v2PzAvXe8xppq9oh9t5TDFGjppn"; } }
        public static string SuccessResponseMessage { get { return "ok"; } }
        public static string FailResponseMessage { get { return "fail"; } }
        /// <summary>
        /// 免登陆URL
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GenerateURL(GenerateURLRequest request)
        {
            if (request == null)
            {
                request = new GenerateURLRequest();
            }
            if(string.IsNullOrEmpty(request.uid))
            {
                request.credits = 0;
                request.uid = "not_login";
            }
            const string baseUrl = "http://www.duiba.com.cn/autoLogin/autologin";
            Dictionary<string, string> paramsDic = new Dictionary<string, string>();
            paramsDic.Add("uid", request.uid);
            paramsDic.Add("credits", request.credits.ToString());
            paramsDic.Add("appKey", AppKey);
            paramsDic.Add("timestamp", DateTime.Now.ToTimesTamp().ToString());
            if (!string.IsNullOrEmpty(request.redirect))
            {
                paramsDic.Add("redirect", request.redirect);
            }
            paramsDic.Add("vip", request.vip.ToString());
            if(!string.IsNullOrEmpty(request.alipay))
            {
                paramsDic.Add("alipay", request.alipay);
            }
            if (!string.IsNullOrEmpty(request.realname))
            {
                paramsDic.Add("realname", request.realname);
            }
            if (!string.IsNullOrEmpty(request.qq))
            {
                paramsDic.Add("qq", request.qq);
            }
            if (!string.IsNullOrEmpty(request.phone))
            {
                paramsDic.Add("phone", request.phone);
            }
            if(!string.IsNullOrEmpty(request.dbredirect))
            {
                paramsDic.Add("redirect", request.dbredirect);
            }
            paramsDic.Add("sign", Commond.GenerateParamASCMD5(AppSecret, paramsDic));
            return string.Format("{0}?{1}", baseUrl, Commond.GenerateUrlParams(paramsDic));
        }
        /// <summary>
        /// 扣积分
        /// </summary>
        /// <param name="request"></param>
        /// <param name="func">执行生成订单、扣积分（更新订单号和当前积分）等处理</param>
        /// <returns></returns>
        public static MinusPointsResponse MinusPoints(string request, out Dictionary<string, string> requestDic)
        {
            MinusPointsResponse rel = new MinusPointsResponse();
            requestDic = new Dictionary<string, string>();
            try
            {
                if (RequestSignVerify(request, out requestDic))
                {
                    if (!requestDic.ContainsKey("appKey") || string.IsNullOrEmpty(requestDic["appKey"]) || requestDic["appKey"] != AppKey)
                    {
                        throw new Exception("appKey not match");
                    }
                    if (!requestDic.ContainsKey("timestamp") || string.IsNullOrEmpty(requestDic["timestamp"]))
                    {
                        throw new Exception("timestamp can't be null");
                    }
                    if (!requestDic.ContainsKey("uid") || string.IsNullOrEmpty(requestDic["uid"]))
                    {
                        throw new Exception("uid can't be null");
                    }
                    if (!requestDic.ContainsKey("waitAudit") || string.IsNullOrEmpty(requestDic["waitAudit"]))
                    {
                        throw new Exception("waitAudit can't be null");
                    } 
                    rel.status = "ok";
                    rel.errorMessage = "";
                }
                else
                {
                    throw new Exception("sign verify fail");
                }
            }
            catch (Exception ex)
            {
                rel.status = "fail";
                rel.errorMessage = ex.Message+"("+request+")";
            }
            return rel;
        }
        /// <summary>
        /// 请求签名验证
        /// </summary>
        /// <param name="appSecret"></param>
        /// <param name="requestUrl"></param>
        /// <returns></returns>
        public static bool RequestSignVerify(string requestUrl)
        {
            Dictionary<string, string> temp;
            return RequestSignVerify(requestUrl, out temp);
        }
        /// <summary>
        /// 请求签名验证，获取参数字典
        /// </summary>
        /// <param name="appSecret"></param>
        /// <param name="requestUrl"></param>
        /// <param name="requestDic"></param>
        /// <returns></returns>
        public static bool RequestSignVerify(string requestUrl, out Dictionary<string, string> requestDic)
        {
            var rel = requestUrl.Remove(0, requestUrl.IndexOf('?') + 1).Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
            var relDic = new Dictionary<string, string>();
            requestDic = relDic;
            foreach (var param in rel)
            {
                var kp = param.Split('=');
                if (kp.Length == 2)
                {
                    relDic.Add(kp[0], HttpUtility.UrlDecode(kp[1]));
                }
                else
                {
                    return false;
                }
            }
            if (relDic.ContainsKey("sign"))
            {
                var sign = relDic["sign"];
                relDic.Remove("sign");
                return Commond.GenerateParamASCMD5(AppSecret, relDic) == sign;
            }
            return false;
        }
        /// <summary>
        /// 获取兑吧订单状态
        /// </summary>
        /// <param name="orderNum"></param>
        /// <param name="bizld"></param>
        /// <returns></returns>
        public static OrderStatusResponse GetOrderStatus(string orderNum,string bizld)
        {
            var rel = new OrderStatusResponse{ Success=false };
            string baseUrl = "http://www.duiba.com.cn/status/orderStatus";
            var paramDic = new Dictionary<string, string>
            {
                {"appKey",AppKey},
                {"timestamp",DateTime.Now.ToTimesTamp().ToString()},
                {"orderNum",orderNum},
                {"bizId",bizld},
            };
            var sign = Core.Commond.GenerateParamASCMD5(AppSecret,paramDic);
            paramDic.Add("sign", sign);
            var queryUrl = string.Format("{0}?{1}", baseUrl, Core.Commond.GenerateUrlParams(paramDic));
            var res = Commond.HttpGetResponse(queryUrl);
            rel = Newtonsoft.Json.JsonConvert.DeserializeObject<OrderStatusResponse>(res);
            return rel;
        }
        /// <summary>
        /// 更新审核状态
        /// </summary>
        /// <param name="passOrderNums">通过的订单号</param>
        /// <param name="rejectOrderNums">为通过的订单号</param>
        /// <returns></returns>
        public static bool UpdateAuditStatus(string[] passOrderNums, string[] rejectOrderNums)
        {
            string baseUrl = "http://www.duiba.com.cn/audit/apiAudit";
            var paramDic = new Dictionary<string, string>
            {
                {"appKey",AppKey},
                {"timestamp",DateTime.Now.ToTimesTamp().ToString()},
                {"passOrderNums",string.Format("{0}",string.Join(",",passOrderNums??new string[]{""}))},
                {"rejectOrderNums",string.Join(",",rejectOrderNums??new string[]{""})},
            };
            var sign = Commond.GenerateParamASCMD5(AppSecret, paramDic);
            paramDic.Add("sign", sign);
            var queryUrl = string.Format("{0}?{1}", baseUrl, Commond.GenerateUrlParams(paramDic));
            try
            {
                var res = Commond.HttpGetResponse(queryUrl);
                dynamic rel = Newtonsoft.Json.JsonConvert.DeserializeObject(res);

                return rel.success ?? false;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }
}
